package com.lin.csdn.controller;

import com.lin.csdn.service.impl.TalkService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/talkServlet")
public class TalkServlet extends HttpServlet {
    /**
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     *
     * 0：获取用户的聊天记录 GetOwnTalk
     * 1:新增聊天记录  AddTalk
     * 2：获取聊天对象的聊天记录 GetOppositeTalk
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding ("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        //建立功能代表的code调用
        String GetOwnTalk="0";
        String AddTalk="1";
        String GetOppositeTalk="2";
        //获取req数据
        String code =req.getParameter("code");

        List<Object> data = null;
        TalkService talkService=new TalkService();
        JSONArray array=new JSONArray();
        PrintWriter writer = resp.getWriter(); //响应流

        //根据需求调用各自的方法
        if(code.equals(GetOwnTalk)){
            String targetName=req.getParameter("targetName");
            String userName=req.getParameter("userName");
            data=talkService.search(userName,targetName);
        }
        else if(code.equals(AddTalk)){
            String targetName=req.getParameter("targetName");
            String userName=req.getParameter("userName");
            String context=req.getParameter("context");
            //添加聊天需要的是内容，发送方以及接送方的信息
            talkService.addTalk(userName,targetName,context);
            JSONObject object=new JSONObject();
            //返回成功信息
            object.put("result","200");
            writer.print(object);
        }
        else if(code.equals(GetOppositeTalk)){
            String targetName=req.getParameter("targetName");
            String userName=req.getParameter("userName");
            data=talkService.searchUserTalk(userName,targetName);
        }
        if(code.equals(GetOwnTalk)||code.equals(GetOppositeTalk)){
            //如果是查询聊天信息，则打印响应的数据
            for(int i=0;i<data.size();i++){
                JSONObject object=new JSONObject();
                object.put("id",data.get(i));
                i++;
                object.put("context", data.get(i));
                i++;
                object.put("date",data.get(i));
                array.put(object);
            }
            writer.print(array);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
